import Schemas from '../schemas';
import { Mongo } from 'meteor/mongo';
import { check } from 'meteor/check';

const ChannelMembers = new Mongo.Collection('channelMembers');

ChannelMembers.attachSchema(Schemas.ChannelMember);

if (Meteor.isServer) {
  Meteor.publish('check.channel.member', function(channel_id, user_id) {
    return ChannelMembers.find({channel_id: channel_id, user_id: user_id});
  });
}

// 检查用户是否已经加入频道
const isMember = (channel_id, user_id) => {
  check(channel_id, String);
  check(user_id, String);

  if (Meteor.isClient) {
    Meteor.subscribe('check.channel.member', channel_id, user_id);
  }

  const result = ChannelMembers.find({channel_id: channel_id, user_id: user_id});

  if (result.count() === 1) {
    return true;
  } else {
    return false;
  }
};

export { ChannelMembers, isMember };
